    package com.qdd01.interception;

    import com.qdd01.entity.User;
    import com.qdd01.util.BaseContext;
    import com.qdd01.util.JwtUtil;
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.servlet.http.HttpServletResponse;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;

    @Component
    @Slf4j
    public class adminJWTinterception implements HandlerInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String token = request.getHeader("Authorization");
    /*        log.info("Received token: {}", token);*/

            if (token == null || token.isEmpty()) {
                log.warn("No token provided");
                response.setStatus(401);
                return false;
            }

            // 如果使用了 Bearer 认证方案，需要去掉 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            try {
                // 验证 token
                User user = JwtUtil.extractUser(token);
                BaseContext.setCurrentId(user.getId());
                return true;
            } catch (Exception e) {
                log.error("Token validation failed", e);
                response.setStatus(401);
                return false;
            }
        }


        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            BaseContext.removeCurrentId();
        }
    }
